package com.yiboshi.rehrs.util;


import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class JwtUtil {

    static final String SECRET = "12+_)@#$3216478%";



    private static String jwtString(int days, HashMap<String, Object> map) {
        Date now = new Date(System.currentTimeMillis());
        String jwt = Jwts.builder()
                //.setId(memberId)
                .setClaims(map)
                //.setIssuedAt(now)
                // 1天
                .setExpiration(new Date(now.getTime() + (TimeUnit.DAYS.toMillis(days))))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        //jwt前面一般都会加Bearer
        return jwt;
    }

    //1天有效期
    public static String generateToken(String v) {
        HashMap<String, Object> map = new HashMap<>();
        //you can put any data in the map
        map.put("t", v);
        return jwtString(1, map);
    }
    public static String getToken(String jwtStr) {
        if(StrUtils.isBlank(jwtStr)){
            return null;
        }
        if(jwtStr.startsWith("Bearer ")){
            jwtStr = jwtStr.substring(7);
        }
        return getParams(jwtStr,"t");
    }

    public static boolean validateToken(String tokenJwt) {
        return !CollectionUtils.isEmpty(getParams(tokenJwt));
    }

    @SneakyThrows
    public static <T> T getParams(String jwt,String key) {
        Map<String, Object> params = getParams(jwt);
        return Optional.ofNullable(params).map(s->params.get(key))
                .map(o->(T)o).orElse(null);
    }

    @SneakyThrows
    public static Map<String, Object> getParams(String ciphertext) {
        try{
           if(StrUtils.isBlank(ciphertext)||ciphertext.length()<20){
               return Collections.emptyMap();
           }
            Map byCache10Hour = CacheUtils.getByCache10Hour(ciphertext, Map.class);

            if(byCache10Hour!=null){
               return byCache10Hour;
           }
            // parse the token.
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(ciphertext)
                    .getBody();
            CacheUtils.putByCache10Hour(ciphertext,body);
            return body;
        }catch (JwtException e){
            log.error("ciphertext:{}",ciphertext,e.getMessage());
        }
        return Collections.emptyMap();
    }

}